#include <stdio.h>
#include <pthread.h>

#include <signal.h>

#define NUM_THREADS         5

void *thread_func(void *arg) {
    int id = *(int *)arg;

    printf("Thread %d started\n", id);
    for (int i = 0; i < 5; ++i) {
        printf("Thread %d: %d\n", id, i);
    }

    while(1);

    printf("Thread %d finished\n", id);

    return NULL;
}

int main() {
    pthread_t threads[NUM_THREADS];
    int ids[NUM_THREADS];

    for (int i = 0; i < NUM_THREADS; ++i) {
        ids[i] = i + 1;
        int rc = pthread_create(&threads[i], NULL, thread_func, &ids[i]);
        if (rc) {
            printf("Thread creation failed: %d\n", rc);
            return 1;
        }
    }

    // Wait for user input before killing threads
    printf("Press any key to kill threads\n");
    getchar();

    for (int i = 0; i < NUM_THREADS; ++i) {
        // kill thread with SIGTERM even if it's dead loop
        pthread_kill(threads[i], SIGTERM);
    }

    for (int i = 0; i < NUM_THREADS; ++i) {
        pthread_join(threads[i], NULL);
    }

    printf("Main thread finished\n");

    return 0;
}
